<template>
    <div class="app-container">
        <levelbar></levelbar>
        <TableLayout form-title="班级信息">
            <el-form :model="classIdInfofamily" slot="form" label-width="80px" label-position="left">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <span v-cloak>班级名称:{{classIdInfofamily.className}}</span>
                    </el-col>
                    <el-col :span="6" v-if="classIdInfofamily.gradeName">
                        <span v-cloak>年级:{{classIdInfofamily.gradeName}}</span>
                    </el-col>
                    <el-col :span="6">
                        <span v-cloak>班级编号:{{classIdInfofamily.classNum}}</span>
                    </el-col>
                    <el-col :span="6">
                        <span v-cloak>班级码:{{classIdInfofamily.classCode}}</span>
                    </el-col>
                </el-row>
            </el-form>
            <div class="table-title" slot="table-title">
                <div>
                <el-button @click="addNewClass">新增</el-button>
                <el-button @click="allJustment">集体调班</el-button>
                <el-button @click="btnImport">批量导入</el-button>
                <el-button @click="delTab">批量删除</el-button>
                </div>
                <!-- <el-button @click="leaveBtn">离班</el-button> -->
            </div>
            <el-table :data="studentList" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" v-loading="loading" border>
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="学生姓名" prop="studentName"  align="center">
                  <template scope="scope">
                    <span class="btn-success link-src" @click="btnSee(scope.row)">{{!scope.row.studentName ? '--' : scope.row.studentName}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="e学云ID号" prop="exueCode"  align="center">
                  <template scope="scope">
                    {{!scope.row.exueCode ? '--' : scope.row.exueCode}}
                  </template>
                </el-table-column>
                <el-table-column label="性别" align="center">
                  <template scope="scope">
                        {{scope.row.sex == 0 ? '男' : scope.row.sex == 1 ? '女' : '未设置'}}
                  </template>
                </el-table-column>
                <el-table-column label="绑定家长数" prop="parentNum"  align="center">
                  <template scope="scope">
                    {{!scope.row.parentNum ? '--' : scope.row.parentNum}}
                  </template>
                </el-table-column>
                <el-table-column label="最后登陆时间" show-overflow-tooltip align="center">
                  <template scope="scope">
                        {{!scope.row.lastLoginTime ? '--' : scope.row.lastLoginTime}}
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="adjustment(scope.row)">调班</el-button>
                        <el-button type="text" class="btn-success" @click="delClass(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>

        <!-- 调班 -->
        <adjustmentDialog @adjustmentSon="adjustmentSon" v-if="adjustmentData.dialogFormVisible" :adjustmentData="adjustmentData"></adjustmentDialog>

        <!-- 批量导入 -->
        <importBatch @importData="importData" v-if="importList.dialogFormVisible" :importList="importList"></importBatch>

        <!-- 离班 -->
        <!-- <el-dialog title="提示" :visible.sync="leaveData.dialogFormVisible" size="tiny">
            <span>确定离开该班级？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="leaveCancel">取 消</el-button>
                <el-button type="primary" @click="leaveConfirm">确 定</el-button>
            </span>
        </el-dialog> -->

        <!-- created by cuihd at 20180712 优化集体调班/批量导入学生 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>
<script>
import Levelbar from "../layout/Levelbar";
import TableLayout from "components/TableLayout";
import { mapState, mapActions, mapGetters } from "vuex";
import {
  findStudentClassInfosByPage,
  removeStudent,
  shiftStudent,
  findClassInfoByClassId,
  importStudentProgress,
  changeStudentClassProgress,
  removeStudentProgress
} from "api/classAll";
import adjustmentDialog from "./comps/adjustmentDialog";
import importBatch from "./comps/importBatch";

export default {
  name:"studentList",
  components: { Levelbar, TableLayout, adjustmentDialog, importBatch },
  created() {
    this.getstudentList();
    this.findInfoClassId();
  },
  computed: {
    ...mapState({
      config: state => state.config.table,
      cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
    }),
    ...mapGetters(["uid"]),
  },
  watch: {// 局部刷新列表
        cacheUpdated(val) {
            if (val) {
              this.getstudentList();
              this.findInfoClassId();
            }
        }
    },
  data() {
    return {

      //班级信息集合
      classIdInfofamily: {},
      loading: true,
      listQuery: {

        //分页
        page: 1,
        total: 0
      },

      //表单数据集合
      studentList: [],

      //调班子组件
      adjustmentData: {
        dialogFormVisible: false,
        id: null,
        family: {}
      },

      //批量导入子组件
      importList: {
        dialogFormVisible: false,
        classId: ""
      },

      //多选集合
      multipleSelection: [],

      //离班子组件状态
      // leaveData: {
      //   dialogFormVisible: false
      // }

      /**
       * created by cuihd at 20180709
       * 优化批量删除教师
       * 添加相关变量
       */
      dialogTitle: '正在集体调班...',
      dialogTimeout: false,
      progress: 0
    };
  },
  methods: {
    //全局获取行数
    ...mapActions(["ChangePageSize"]),
    handleSizeChange(val) {
      this.loading = true;
      this.listQuery.page = 1;
      this.ChangePageSize(val);
      this.getstudentList();
    },
    findInfoClassId() {
      findClassInfoByClassId(this.$route.params.id).then(data => {
        this.classIdInfofamily = data.data.content;
        // this.schoolId = this.classIdInfofamily.schoolId;
      });
    },
    handleCurrentChange(val) {
      this.loading = true;
      this.listQuery.page = val;
      this.getstudentList();
    },
    getstudentList() {
      if(this.$route.params.id){
        this.loading = true;
        findStudentClassInfosByPage(
        this.listQuery.page,
        this.config.pageSize,
        this.$route.params.id
      ).then(response => {
        this.loading = false;
        this.studentList = response.data.content.list;
        if(!response.data.content){
          this.studentList = [];
          this.listQuery.total = 0;
        }else{
          this.listQuery.total = response.data.content.pagination.total;
        }
      });
      }
    },
    btnSee(val) {
      //跳转到学生管理
      this.$router.push({ path: `/studentManage/studentInforPage/${val.studentId}/${this.$route.params.id}`});
    },
    adjustment(val) {
      this.adjustmentData.id = [val.studentId];
      if (this.adjustmentData.id.length == 0) {
        this.$message({
          message: "请选择调班的学生",
          type: "warning"
        });
      } else {
        this.adjustmentData.dialogFormVisible = true;
        this.adjustmentData.family = this.classIdInfofamily;
      }
    },
    allJustment() {
      this.adjustmentData.id = this.tabFilter("studentId");
      if (this.adjustmentData.id == 0) {
        this.$message({
          message: "请选择调班的学生",
          type: "warning"
        });
      } else {
        this.adjustmentData.dialogFormVisible = true;
        this.adjustmentData.family = this.classIdInfofamily;
      }
    },
    adjustmentSon(val) {
      if (val.isTrue) {
        this.adjustmentData.dialogFormVisible = false;
        this.dialogTitle = '正在调班中...';
        this.dialogTimeout = true;
        this.progress = 0;
        this.batchProgress(val);       
      }else{
        this.getstudentList();
      }
    },
    // created by cuihd at 20180713
    // 轮询接口获取未处理的数量
    batchProgress(obj) { // 递归轮询
        let totalNum = Number(obj.totalNum); // 强转成number类型
        changeStudentClassProgress(obj.timeStamp, obj.fromClassId, obj.toClassId).then(res => {
            if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                if (res.data.content != 0) {
                    this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                    setTimeout(() => {
                        this.batchProgress(obj);
                    }, 1000);
                } else {
                    this.dialogTitle = '调班成功';
                    this.progress = 100;
                    setTimeout(() => {                       
                        this.dialogTimeout = false;
                        this.$store.dispatch('UpdateCache',true);
                        this.getstudentList();
                    }, 500)
                }
            }else{
                this.dialogTimeout = false;
                this.$message({
                    message: '调班失败！',
                    type: 'error'
                });
                this.getstudentList();
            }          
        }).catch(err => {
            //console.log(err);
        })
    },
    // created by cuihd at 20180711
    // 轮询接口获取未导入学生的数量
    batchImportProgress(obj) { // 递归轮询
        let totalNum = Number(obj.totalNum); // 强转成number类型
        importStudentProgress(obj.timeStamp, obj.classId).then(res => {
            if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                if (res.data.content != 0) {
                    this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                    setTimeout(() => {
                        this.batchImportProgress(obj);
                    }, 1000);
                } else {
                    this.dialogTitle = '批量导入成功';
                    this.progress = 100;
                    setTimeout(() => {                       
                        this.dialogTimeout = false;
                        this.$store.dispatch('UpdateCache',true);
                        this.getstudentList();
                    }, 500)
                }
            }else{
                this.dialogTimeout = false;
                this.$message({
                    message: '批量导入失败！',
                    type: 'error'
                });
                this.getstudentList();
            }          
        }).catch(err => {
            //console.log(err);
        })
    },
    delClass(val) {
      this.$confirm("确定删除该学生吗？", " ", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        // type: "warning"
      })
        .then(() => {
          let delId = [];
          delId.push(val.studentClassMapId);
          removeStudent(delId).then(data => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getstudentList();
            this.$store.dispatch('UpdateCache',true);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    addNewClass() {
      this.$router.push({
        path: `/classStudent/addNewStudent/${this.classIdInfofamily.schoolId}/${this.classIdInfofamily.classId}/${this.$route.params.id}`,
        // params: {
        //   schoolId: this.classIdInfofamily.schoolId,
        //   classId: this.classIdInfofamily.classId,
        //   id: this.$route.params.id
        // }
      });
    },
    btnImport() {
      this.importList.dialogFormVisible = true;
      this.importList.classId = this.$route.params.id;
    },
    importData(val) {
      if (val.isTrue) {
        this.adjustmentData.dialogFormVisible = false;
        this.dialogTitle = '正在批量导入学生...';
        this.dialogTimeout = true;
        this.progress = 0;
        this.batchImportProgress(val);
      }
    },
    
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delTab() {
      let studentIdArry = this.tabFilter("studentClassMapId");
          if (studentIdArry.length == 0) {
            this.$message({
              message: "请选择删除的学生",
              type: "warning"
            });
          } else {
            this.$confirm("将删除选中学生，是否继续？", " ", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: ""
            }).then(() => {
              this.loading = true;
              removeStudent(studentIdArry).then(res => {
                  /**
                   * created by cuihd at 20180711
                   * 优化批量删除学生
                   * 添加相关变量
                   */
                  if (res.data.content) {
                    let timeStamp = res.data.content.timeStamp;
                    let totalNum = res.data.content.totalNum;
                    this.dialogTitle = '正在批量删除学生...';
                    this.dialogTimeout = true;
                    this.progress = 0;
                    this.batchDelProgress(timeStamp, totalNum);
                  }                 
                });
              }).catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除"
              });
            });
          }

      // this.$confirm("确定删除该学生吗？", " ", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: ""
      // })
      //   .then(() => {
          //多个删除调用 tabFilter(),返回数组
          // let studentIdArry = this.tabFilter("studentClassMapId");
          // if (studentIdArry.length == 0) {
          //   this.$message({
          //     message: "删除不能为空",
          //     type: "warning"
          //   });
          // } else {
            // removeStudent(studentIdArry).then(data => {
            //   this.$message({
            //     type: "success",
            //     message: "删除成功!"
            //   });
            //   this.getstudentList();
            // });
          // }
        // })
    },

    // created by cuihd at 20180711
    // 轮询接口获取未删除学生的数量
    batchDelProgress(timeStamp, totalNum) { // 递归轮询
        totalNum = Number(totalNum); // 强转成number类型
        removeStudentProgress(timeStamp).then(res => {
            if(res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null){
                if (res.data.content != 0) {
                    this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                    setTimeout(() => {
                        this.batchDelProgress(timeStamp, totalNum);
                    }, 1000);
                } else {
                    this.dialogTitle = '批量删除成功';
                    this.progress = 100;
                    setTimeout(() => {                       
                        this.dialogTimeout = false;
                        this.$store.dispatch('UpdateCache',true);
                        this.getstudentList();
                    }, 500)
                }
            }else{
                this.dialogTimeout = false;
                this.$message({
                    message: '批量删除失败！',
                    type: 'error'
                });
                this.getstudentList();
            }          
        }).catch(err => {
            //console.log(err);
        })
    },
    tabFilter(val) {
      let idList = [];
      this.multipleSelection.forEach(item => {
        idList.push(item[val]);
      });
      return idList;
    },

    // leaveBtn() {
    //   if (this.tabFilter("studentClassMapId").length == 0) {
    //     this.$message({
    //       message: "离班不能为空",
    //       type: "warning"
    //     });
    //   } else {
    //     this.leaveData.dialogFormVisible = true;
    //   }
    // },
    // leaveConfirm() {
    //   shiftStudent(this.tabFilter("studentClassMapId")).then(data => {
    //     this.getstudentList();
    //     this.tabFilter();
    //     this.leaveData.dialogFormVisible = false;
    //   });
    // },
    // leaveCancel() {
    //   this.leaveData.dialogFormVisible = false;
    // }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  .app-levelbar {
    height: 35px;
  }
  .el-form {
    background: #fff;
    padding-bottom: 50px;
  }
}
</style>
